# -*- coding: utf-8 -*-
import logging
import json
from datetime import timedelta

from django.views.decorators.http import require_GET, require_POST

from common.stats import MG_BIGBANG_COLL as mg
from common.utils.decorator import response_wrapper
from common.utils.api import token_required
from common.utils.tz import get_utc_date
from common.utils.exceptions import ParamError
from common.utils.decorator import mongo_wrapper

_LOGGER = logging.getLogger(__name__)


@require_GET
@response_wrapper
@token_required
@mongo_wrapper
def get_recharge_list(req):
    query_dct = req.GET.dict()
    page = int(query_dct.get('page', 0))
    size = int(query_dct.get('size', 0))
    limit = 20 if size <= 0 else size
    skip = 0 if page <= 0 else (page - 1) * limit
    query_dct = req.GET.dict()
    for k in 'start_date', 'end_date':
        query_dct[k] = get_utc_date(query_dct.get(k))

    if query_dct['start_date'] == query_dct['end_date']:
        query_dct['end_date'] += timedelta(days=1)

    cond = {"updated_at": {
        "$gte": query_dct['start_date'], "$lt": query_dct['end_date']},
        "recharge.total": {"$gt": 0}}
    results = mg.daily_stats.find(
        cond, {"user_id": 1, "recharge.total": 1}
    ).skip(skip).limit(limit).sort([("recharge.total", -1)])
    total_count = mg.daily_stats.aggregate([
        {"$match": cond},
        {"$group": {"_id": None, "count": {"$sum": 1}}}
    ])
    total_count = total_count.next().get("count", 0) if total_count.alive else 0

    resp_items = []
    for result in results:
        resp_items.append({"user_id": result["user_id"],
                           "recharge": result["recharge"]["total"]})

    return {'list': resp_items, 'page': page or 1,
            'size': len(resp_items), 'total_count': total_count}
